# -*- coding:utf-8 -*-

from django.views import View
from django.shortcuts import render
import django.http
from api.models import Apis
from json import dumps, JSONEncoder
import datetime
from .tasks import interfaceTest1
# Create your views here.
# 单一接口管理
class ApiListView(View):
    """
    @description: 这是一个测试接口，用于返回json格式的数据
    @param {type}
    @return: json
    """
    def post(self, request):
        """
        @description: 用于处理post请求
        @param {type}
        @return: json
        """
        json_list = self.getApiList()
        # print("这是POST_list:", json_list)
        # json_dumps = dumps(json_list, cls=DateEncoder)
        # json_list = JsonResponse(json_dumps)
        # return render(request, 'testApi.html', json_list)
        return django.http.HttpResponse(dumps(json_list, cls=DateEncoder), content_type="application/json,charset=utf-8")

    def get(self, request):
        """
        @description: 用于处理get请求
        @param {type}
        @return:
        """
        json_list = self.getApiList()
        # print("这是GET_list:", json_list)
        json_dumps = dumps(json_list, cls=DateEncoder)
        return django.http.HttpResponse(dumps(json_dumps, cls=DateEncoder), content_type="application/json,charset=utf-8")

    def getApiList(self):
        """
        @description: 查询接口用例数据
        @param {type}
        @return:
        """
        json_list = []
        apis_list = Apis.objects.all()
        for api in apis_list:
            # 获取商品的每个字段， 键值对形式
            json_dict = {'name': api.apiname, 'url': api.apiurl, 'paramvalue': api.apiparamvalue,
                         'method': api.apimethod, 'result': api.apiresult, 'response': api.apiresponse,
                         'status': api.apistatus, 'create_time': api.create_time}
            json_list.append(json_dict)
        return json_dict


class ApiTestView(View):
    """
    @description: 单接口测试入口
    @param {type}
    @return: 跳转到指定页面
    """
    def sendApi(self, request, case_id = None):
        print('================' + str(case_id))
        # api_list = {}
        api_list = list(Apis.objects.filter(id=case_id).values())
        test_result = interfaceTest1(api_list)
        return render(request, 'testApi.html', context = test_result)


# 重写json
class DateEncoder(JSONEncoder):
    """
    重写json序列化的类，用于自定义序列化日期和时间
    """
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return JSONEncoder.default(self, obj)
